package com.leetcode;

import com.leetcode.common.ListNode;

/**
 * 61. 旋转链表
 *
 * @author fy
 * @date 2022/4/11 17:57
 */
public class Solution61 {

    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null || k <= 0) {
            return head;
        }
        ListNode dummyHead = new ListNode(-1, head);
        ListNode cur = dummyHead.next;
        int length = 0;
        while (cur != null) {
            length++;
            cur = cur.next;
        }
        int n = k % length;
        if (n == 0) {
            return head;
        }
        cur = dummyHead.next;
        for (int i = 1; i < length - n; i++) {
            cur = cur.next;
        }
        // 当前节点为待切断拼接链的前一个节点
        ListNode prev = cur;
        ListNode head1 = dummyHead;
        ListNode head2 = prev.next;
        // 切断链
        prev.next = null;
        ListNode next = head1.next;
        head1.next = head2;
        while (head2.next != null) {
            head2 = head2.next;
        }
        head2.next = next;
        return dummyHead.next;
    }
    
}
